import { jsonArray } from '@/api/productApi/file'
import Vue from 'vue'

export function treeData(list, cascaderIdList = []) {
	list.forEach(item => {
		item.cascaderIdList = [...cascaderIdList]
		item.cascaderIdList.push(item.fieldId)
		if (item.childNodeList && Array.isArray(item.childNodeList) && !item.childNodeList.length) {
			Vue.delete(item, 'childNodeList')
		}
		if (item.childNodeList && Array.isArray(item.childNodeList) && item.childNodeList.length) {
			treeData(item.childNodeList, item.cascaderIdList)
		}
	})
	return list
}

// 处理多维数组
export function processingRawData(list) {
	// 1.拿出顶级数据
	const treeData = list.filter(item => item.parentId === '0')

	// 2.去除顶级数据在循环
	const listData = list.filter(item => item.parentId !== '0')

	// 3.取得所有数据的ID
	let listNum = []
	listData.forEach(item => {
		listNum.push(Number(item.fieldId))
	})

	// 4.将要循环的数组去重
	listNum = listNum.filter(function (item, index) {
		return listNum.indexOf(item) === index
	})

	// 5.形成多维数组
	/*
	因为数组是引用类型数据类型，子级的改动会影响到所有引用他的地方,此时将 “5-2”
	*/
	for (let i = 0; i < listNum.length; i++) {
		listData.forEach(item => {
			// 5-1.一层循环，生成数组，保证每组数据都存在一个childNodeList数组
			if (listNum[i] === Number(item.fieldId)) {
				item.childNodeList = []
				// 5-2.二层循环，将所有父级ID === 当前一层循环数据当前组ID的存入一层循环数据当前组的childNodeList
				listData.forEach(items => {
					if (Number(items.parentId) === Number(item.fieldId)) {
						item.childNodeList.push(items)
					}
				})
			}
		})
	}

	// 6.将步骤数据嵌入到与顶级数据 raiseType 相同的数据
	treeData.forEach(item => {
		item.childNodeList = listData.filter(items => item.fieldId === items.parentId)
	})

	const data = jsonArray(treeData)

	return data
}

// 将字段级数据置空，防止页面加载卡顿
export function dataProcessing(list) {
	const data = jsonArray(list)
	data.forEach(item => {
		item.childNodeList.forEach(items => {
			if (items.childNodeList && Array.isArray(items.childNodeList) && items.childNodeList.length) {
				items.childNodeList = []
			}
		})
	})

	return data
}

// 将改角色可见字段包装成后台需要的数据格式
export function graphiqlParams(obj, list) {
	const data = {
		fundRaiseType: obj.fundRaiseType,
		fundSysCode: obj.fundSysCode,
		manageStatus: '0'
	}
	const properList = list.find(item => item.raiseType === obj.fundRaiseType).childNodeList
	const stepStrList = []
	for (const i in properList) {
		stepStrList.push(treeStr(properList[i]))
	}
	data.graphQlParams = stepStrList.join(',')
	return data
}
function treeStr(obj) {
	// 下属基金
	const branchShareList = ['fundCode', 'fundGradName', 'fundGradFullName', 'subFundType', 'shareCategory', 'estimatedRaisedAmount', 'estimatedAnnualRate']
	// 费率
	const feeRateInfoList = ['feeRateId', 'feeRateType', 'startSection', 'endSection', 'feeRate', 'feeRateUnit', 'belongFundRatio', 'belongFundRatioUnit', 'remark', 'fundCode', 'subFundType', 'salesServiceFeeAlgorithm']
	// 基金经理
	const fundManagerInfoList = [
		'fundManagerId',
		'managerId',
		'workflowStartDate',
		'workflowStatus',
		'workflowId',
		'startDate',
		'endDate',
		'entryNoticeDate',
		'leaveNoticeDate',
		'fundChangeHistory',
		'remarks',
		'fundType',
		'manageStatus',
		'entryReportBodDate',
		'entryBodResolutionDate',
		'entrySubmittedDate',
		'entrySocietyReplyDate',
		'entryScanPiece',
		'leaveReportBodDate',
		'leaveBodResolutionDate',
		'leaveSubmittedDate',
		'leaveSocietyReplyDate',
		'leaveScanPiece',
		'generalMeetingReplyDate',
		'managerName',
		'oaId',
		'email',
		'phone',
		'mobile',
		'gender',
		'birthYear',
		'idType',
		'idNo',
		'entryYear',
		'servingDate',
		'leaveDate',
		'education',
		'resumeDocId',
		'resume',
		'remark',
		'departmentId',
		'job',
		'entryFundManagerDate',
		'entryAccountManagerDate',
		'entryResearcherDate',
		'managerType',
		'fundManagerType',
		'idEndDate',
		'stockEntryStartDate',
		'yearsOfEmployment'
	]

	let propertyStr = `${obj.fieldCode} {`
	if (obj.childNodeList && Array.isArray(obj.childNodeList) && obj.childNodeList.length) {
		const list = []
		obj.childNodeList.forEach(item => {
			if (!item.childNodeList || !Array.isArray(item.childNodeList) || !item.childNodeList.length) { // 判断是否存在子级
				// 判断字段是否是 是否有托管分支机构
				if (!['iscustodyBranchOrgan'].includes(item.fieldCode)) {
					// 判断基金经理
					if (obj.fieldCode === 'fundManagerInfoList') {
						if (fundManagerInfoList.includes(item.fieldCode)) {
							list.push(item.fieldCode)
						}
					} else {
						list.push(item.fieldCode)
					}
				}
			} else {
				const childList = []
				item.childNodeList.forEach(items => {
					if (item.fieldCode === 'branchShareList') { // 判断下属金
						if (branchShareList.includes(items.fieldCode)) {
							childList.push(items.fieldCode)
						}
					} else if (item.fieldCode === 'feeRateInfoList') { // 判断费率
						if (feeRateInfoList.includes(items.fieldCode)) {
							childList.push(items.fieldCode)
						}
					} else {
						childList.push(items.fieldCode)
					}
				})
				propertyStr += `${item.fieldCode}{${childList.join(',')}},`
			}
		})
		propertyStr += list.join(',')
	}
	propertyStr += `}`
	return propertyStr
}

// 数据中文化
export function dataConversionMethod(data, enumData, specialTypeList, newSpaperList) {
	// 基金经理证件类型
	const fundMange = [
		{
			key: '0113',
			value: '外国人永久居留证'
		},
		{
			key: '0199',
			value: '其他人员证件'
		},
		{
			key: '0112',
			value: '外国护照'
		},
		{
			key: '0111',
			value: '社会保障号'
		},
		{
			key: '0110',
			value: '警官证'
		},
		{
			key: '0109',
			value: '文职证'
		},
		{
			key: '0108',
			value: '户口本'
		},
		{
			key: '0107',
			value: '士兵证'
		},
		{
			key: '0106',
			value: '军官证'
		},
		{
			key: '0105',
			value: '港澳台居民居住证'
		},
		{
			key: '0101',
			value: '身份证'
		},
		{
			key: '0102',
			value: '护照'
		},
		{
			key: '0103',
			value: '港澳居民来往内地通行证'
		},
		{
			key: '0104',
			value: '台湾居民来往大陆通行证'
		}
	]

	// 费率计时提点
	const rateCheck = [
		{ typeCode: '1', typeName: '不提取' },
		{ typeCode: '2', typeName: '资产管理计划投资者赎回时' },
		{ typeCode: '3', typeName: '资产管理计划分红时计提' },
		{ typeCode: '4', typeName: '资产管理计划固定开放日计提' },
		{ typeCode: '5', typeName: '资产管理计划临时开放日计提' },
		{ typeCode: '6', typeName: '资产管理计划到期计提' },
		{ typeCode: '7', typeName: '其他计提时点' }
	]

	// 所有枚举字段
	const enumProperty = ['custodyFeeAlgorithm', 'certificateType', 'csrcType', 'associationOpenFrequency', 'productAssetReportType', 'addCreditOrganType', 'addCreditFormType', 'investAdvisorOrgan', 'operateMode', 'openFrequency', 'fiduciaryDuty', 'settleCurrency', 'fundType', 'mixedInvestBias', 'pobcFundType', 'riskGrade', 'isGradFund', 'revenueFeature', 'valuationWay', 'valuationFrequency', 'marketFundType', 'marketTradeSite', 'investTactics', 'feeRateAlgorithm', 'planType', 'productAssetType', 'annuityPlanType', 'annuityTrusteeMode', 'addcreditMeasureType', 'privateFundType', 'peopleMax', 'productSpecialType', 'incomeDisWay']

	// 是/否单选所有字段
	const radioList = ['crossBorderFinancial', 'propertyFundTrust', 'noneHKTIsStopApplyRansom', 'isAssetManagementProduct', 'isAssetSecuritizationBusiness', 'isSpecialAssetReport', 'isInnovateNature', 'isHoldFund', 'isListTransfer', 'isQdii', 'isIndexFund', 'isBreakeven', 'isMutualFund', 'isActiveManage', 'issuerEarlyTermFlag', 'usufructTransferProductFlag', 'currencyMarketFundFlag', 'isAddcreditMeasure', 'isMom', 'isSubAssets', 'isNetWorthProduct', 'isRiskTacticsFund', 'isMarketTrade', 'isPensionTargetFund', 'isEtfJoinFund', 'isFofFund', 'isSponsoredFund', 'isOrganCustom', 'isSingleShare', 'isContainSpclLimit', 'isQuantTactics', 'isCoverTactics', 'isThirdPartyCustody', 'isAchieveReward', 'isHolderMeet', 'isChannelBusiness', 'isSamp', 'isPrivateFund', 'isPensionProduct', 'isInstAcc', 'isBasicPension', 'isSocialSecurity', 'isOccupationalPension', 'isAnnuityPension', 'isStructuredProduct', 'isRiskMeasures']

	// 有/无单选所有字段
	const radioWithWithout = ['customerRedemptionFlag', 'earlyWarnLine', 'stopLossLine', 'maxRetreat', 'otherRiskStep', 'managerIsInvestment', 'managerIsPartake', 'stopLossWarningLine']

	// 管理方式
	const managerStyle = ['managerStyle']

	data.forEach(items => {
		for (const i in items) {
			if (Object.prototype.toString.call(items[i]) === '[object Object]') {
				const obj = items[i]
				const itemProperty = Object.keys(obj)
				itemProperty.forEach(item => { // 处理单选是否
					if (radioList.includes(item)) {
						obj[item] = obj[item] ? obj[item] === '0' ? '是' : '否' : ''
					}
					if (radioWithWithout.includes(item)) {
						obj[item] = obj[item] ? obj[item] === '0' ? '有' : '无' : ''
					}
					if (managerStyle.includes(item)) {
						obj[item] = obj[item] ? obj[item] === '0' ? '集合管理' : '单独管理' : ''
					}
					if (item === 'accrualPointTime') { // 处理费率计时提点
						if (obj[item]) {
							const list = obj[item].split(',')
							const msg = []
							list.forEach(value => {
								msg.push(rateCheck.find(rate => rate.typeCode === value).typeName)
							})
							obj[item] = msg.join(',')
						}
					}
					if (item === 'specialTypeChar') { // 特殊品种
						if (obj[item]) {
							const specialTypeCharList = obj[item].split(',')
							const itemList = []
							specialTypeCharList.forEach(special => {
								const itemObj = specialTypeList.find(it => it.specialTypeId === special)
								itemList.push(itemObj ? itemObj.specialTypeName : special)
							})
							if (itemList.length) {
								obj[item] = [...jsonArray(itemList)].join(',')
							}
						}
					}
					if (enumProperty.includes(item)) {
						if (obj[item]) {
							if (['productSpecialType', 'incomeDisWay'].includes(item)) { // 数组类型枚举
								const list = obj[item].split(',')
								const msg = []
								list.forEach(value => {
									msg.push(enumData[item].find(enumItem => enumItem.typeCode === value).typeName)
								})
								obj[item] = msg.join(',')
							} else { // 字符串型枚举
								const enumItem = enumData[item].find(enumItem => enumItem.typeCode === obj[item])
								obj[item] = enumItem ? enumItem.typeName : ''
							}
						}
					}
					if (item === 'newspaperId') { // 报社
						if (obj[item]) {
							const msg = newSpaperList.find(val => val.newspaperId === obj[item]) ? newSpaperList.find(val => val.newspaperId === obj[item]).newspaper : ''
							obj[item] = msg
						} else {
							obj[item] = ''
						}
					}
				})
				if (i === 'baseInfo') {
					if (Array.isArray(obj.branchShareList) && obj.branchShareList.length) {
						obj.branchShareList.forEach(item => {
							item.isItSuitable = item.estimatedAnnualRate ? '适用' : '不适用'
							if (item.shareCategory) {
								item.shareCategory = enumData.shareCategory.find(obj => obj.typeCode === item.shareCategory).typeName
							}
						})
					}
				}
				items[i] = obj
			} else if (i === 'fundManagerInfoList') { // 处理基金经理证件类型
				if (!!items[i] && Array.isArray(items[i]) && items[i].length) {
					const fundManagerInfoList = items[i]
					fundManagerInfoList.forEach(mange => {
						if (mange.idType) {
							if (![...mange.idType].some(str => str.charCodeAt(0) > 255)) {
								mange.idType = mange.idType ? fundMange.find(value => value.key === mange.idType).value : ''
							}
						}
					})
				}
			}

			if (i === 'baseInfo') { // 处理下属基金
				if (!!items[i].branchShareList && Array.isArray(items[i].branchShareList)) {
					items[i].branchShareList.forEach(sub => {
						if (sub.subFundType) {
							if (![...sub.subFundType].some(str => str.charCodeAt(0) > 255)) {
								sub.subFundTypeChine = enumData.subFundType.find(obj => obj.typeCode === sub.subFundType).typeName
							}
						}
					})
				}
			}
		}
	})

	return data
}

// 所有枚举字段
export const EnumList = [
	{
		propertyKey: 'investAdvisorOrgan',
		enumKey: 'investAdvisorOrgan'
	},
	{
		propertyKey: 'feeRateAlgorithm',
		enumKey: 'feeRateAlgorithm'
	},
	{
		propertyKey: 'custodyFeeAlgorithm',
		enumKey: 'custodyFeeAlgorithm'
	},
	{
		propertyKey: 'csrcType',
		enumKey: 'csrcTypeOrgan'
	},
	{
		propertyKey: 'certificateType',
		enumKey: 'idTypeOrgan'
	},
	{
		propertyKey: 'operateMode',
		enumKey: 'operateMode'
	},
	{
		propertyKey: 'openFrequency',
		enumKey: 'openFrequency'
	},
	{
		propertyKey: 'fiduciaryDuty',
		enumKey: 'fiduciaryDuty'
	},
	{
		propertyKey: 'settleCurrency',
		enumKey: 'settleCurrency'
	},
	{
		propertyKey: 'fundType',
		enumKey: 'fundType'
	},
	{
		propertyKey: 'mixedInvestBias',
		enumKey: 'mixedInvestBias'
	},
	{
		propertyKey: 'pobcFundType',
		enumKey: 'fundType'
	},
	{
		propertyKey: 'riskGrade',
		enumKey: 'riskGrade'
	},
	{
		propertyKey: 'isGradFund',
		enumKey: 'gradFundType'
	},
	{
		propertyKey: 'revenueFeature',
		enumKey: 'revenueFeature'
	},
	{
		propertyKey: 'valuationWay',
		enumKey: 'valuationWay'
	},
	{
		propertyKey: 'valuationFrequency',
		enumKey: 'valuationFrequency'
	},
	{
		propertyKey: 'marketFundType',
		enumKey: 'marketFundType'
	},
	{
		propertyKey: 'marketTradeSite',
		enumKey: 'marketTradeSite'
	},
	{
		propertyKey: 'investTactics',
		enumKey: 'investTactics'
	},
	{
		propertyKey: 'feeRateAlgorithm',
		enumKey: 'feeRateAlgorithm'
	},
	{
		propertyKey: 'planType',
		enumKey: 'planType'
	},
	{
		propertyKey: 'productAssetType',
		enumKey: 'productAssetType'
	},
	{
		propertyKey: 'annuityPlanType',
		enumKey: 'annuityPlan'
	},
	{
		propertyKey: 'annuityTrusteeMode',
		enumKey: 'annuityTrusteeMode'
	},
	{
		propertyKey: 'addcreditMeasureType',
		enumKey: 'addcreditMeasure'
	},
	{
		propertyKey: 'addCreditFormType',
		enumKey: 'addCreditFormType'
	},
	{
		propertyKey: 'addCreditOrganType',
		enumKey: 'addCreditOrganType'
	},
	{
		propertyKey: 'privateFundType',
		enumKey: 'privateFundType'
	},
	{
		propertyKey: 'peopleMax',
		enumKey: 'peopleMax'
	},
	{
		propertyKey: 'productAssetReportType',
		enumKey: 'productAssetReportType'
	},
	{
		propertyKey: 'associationOpenFrequency',
		enumKey: 'associationOpenFrequency'
	},
	{
		propertyKey: 'productSpecialType',
		enumKey: 'productSpecialType',
		type: 'stringArray'
	},
	{
		propertyKey: 'incomeDisWay',
		enumKey: 'incomeDisWay',
		type: 'stringArray'
	}
]

// 将数据转换成可搜索的树形格式
/*
data	中文化之后的基金详细数据
list	可见字段列表
fundRaiseType	产品类型
*/
export function TreeSearch(data, list, fundRaiseType, enumData) {
	const treeData = [] // 存储树形数据
	const allOne = [] // 以为数组，存储所有数据，用来搜索
	let branchShareList = [] // 存储下属基金
	let fundManageProperty = [] // 存储经理披露属性
	let branchShareListProperty = [] // 存储下属基金披露属性
	let rateListShow = false // 判断是否展示费率列表
	let consignerInfo = false // 判断委托人是否展示
	const parent = list.find(roleObj => roleObj.fieldCode === 'branchShareList')
	let branchShareId = '' // 存储下属基金列表字段父id
	if (parent) { // 不管公募专户都进行运算，防止脏数据
		branchShareId = parent.fieldId
	}

	// 先设置顶层数据
	for (const i in data) {
		if (list.some(item => item.fieldCode === i)) {
			const obj = {
				key: i,
				label: list.find(item => item.fieldCode === i).fieldName,
				value: list.find(item => item.fieldCode === i).fieldName
			}
			treeData.push(obj)
		}
	}
	treeData.forEach(item => {
		item.children = []
		if (!['fundManagerInfoList', 'fundFileInfo'].includes(item.key)) { // 处理基础数据类型
			data[item.key] = data[item.key] ? data[item.key] : {} // 一层数据如果不是对象则设置为对象
			const keysList = Object.keys(data[item.key])
			keysList.forEach(items => {
				if (!['__typename', 'branchShareList', 'feeRateInfoList', 'feeRateAlgorithm', 'custodyFeeAlgorithm'].includes(items)) {
					const obj = {
						parentKey: item.key,
						parentValue: item.label,
						label: list.find(roleObj => roleObj.fieldCode === items && branchShareId !== roleObj.parentId).fieldName,
						value: data[item.key][items] ? data[item.key][items] : '',
						key: items
					}
					item.children.push(obj)
					allOne.push(obj)
				} else if (items === 'branchShareList' && fundRaiseType === '1') {
					if (data[item.key][items] && Array.isArray(data[item.key][items]) && data[item.key][items].length) {
						branchShareList = data[item.key][items]
						branchShareListProperty = Object.keys(data[item.key][items][0])
					}
				} else if (items === 'feeRateInfoList') {
					rateListShow = true
				}
				if (items === 'planType' && data[item.key][items] === '单一资产管理计划') {
					consignerInfo = true
				}
			})
		} else if (item.key === 'fundFileInfo') { // 处理文件
			const publicFileType = [ // 公募基金文件类型
				{ title: '承诺函', objName: 'commitmentLetterId' },
				{ title: '特殊承诺函', objName: 'specialLetterId' },
				{ title: '申请报告', objName: 'applyReportId' },
				{ title: '基金合同(申请文件)', objName: 'fundContractId' },
				{ title: '托管协议(申请文件)', objName: 'trustAgreementId' },
				{ title: '招募说明书(申请文件)', objName: 'enlistExplainId' },
				{ title: '内部决议', objName: 'interResultId' },
				{ title: '《法律意见书》', objName: 'lawProposalId' },
				{ title: '《基金产品方案》', objName: 'fundPlanId' },
				{ title: '指数使用协议', objName: 'applyAgreementId' },
				{ title: '交易所无异议函', objName: 'tradeNoActionLetterId' },
				{ title: '《基金合同填报指引》', objName: 'fundContractFillId' },
				{ title: '认购发起份额的承诺函', objName: 'subscribeShareLetterId' },
				{ title: '证监会要求的其他文件.zip', objName: 'otherMaterialsId10' },
				{ title: '募集注册批复', objName: 'raiseLogonReplyId' },
				{ title: '变更注册批复', objName: 'modifyLogonReplyId' },
				{ title: '延期募集批复', objName: 'delayRaiseReplyId' },
				{ title: '成立批复', objName: 'foundReplyId' },
				{ title: '基金合同(募集文件)', objName: 'fundContractId2' },
				{ title: '基金合同摘要', objName: 'fundContractRemark' },
				{ title: '托管协议(募集文件)', objName: 'trustAgreementId2' },
				{ title: '招募说明书(募集文件)', objName: 'enlistExplainId2' },
				{ title: '招募说明书摘要', objName: 'enlistExplainRemark' },
				{ title: '产品资料概要', objName: 'productDataResume' },
				{ title: '期货备忘录', objName: 'otherMaterialsId9' },
				{ title: '清算报告', objName: 'liquInfoationReportId' }
			]
			const specialFileType = [ // 专户产品文件类型
				{ title: '资产管理合同', objName: 'capitalManageContractId' },
				{ title: '计划说明书', objName: 'planExplainId' },
				{ title: '风险揭示书', objName: 'riskProclaimId' },
				{ title: '成立通知书', objName: 'otherMaterialsId' },
				{ title: '到账通知书', objName: 'otherMaterialsId2' },
				{ title: '验资报告（集合计划）', objName: 'otherMaterialsId3' },
				{ title: '如期货备忘录', objName: 'otherMaterialsId4' },
				{ title: '代销协议', objName: 'otherMaterialsId5' },
				{ title: '投顾协议', objName: 'otherMaterialsId6' },
				{ title: '金融产品完成备案的证明材料', objName: 'otherMaterialsId7' },
				{ title: '委托人列表', objName: 'otherMaterialsId8' },
				{ title: '协会备案函', objName: 'filingLetterId' }
			]
			data[item.key] = data[item.key] ? data[item.key] : {} // 一层数据如果不是对象则设置为对象
			const keysList = Object.keys(data[item.key])
			keysList.forEach(items => {
				if (data[item.key][items] && !['__typename'].includes(items)) {
					let fileType = ''
					if (fundRaiseType === '1') {
						fileType = publicFileType.find(file => file.objName === items) ? publicFileType.find(file => file.objName === items).title : ''
					} else if (fundRaiseType === '2') {
						fileType = specialFileType.find(file => file.objName === items) ? specialFileType.find(file => file.objName === items).title : ''
					}
					if (fileType) { // 文件类型存在
						if (data[item.key][items].finalFileId || data[item.key][items].sealedFileId || data[item.key][items].firstFileId) { // 数据中必须存在一个文件的id
							const obj = {
								...data[item.key][items],
								value: fileType,
								key: items,
								parentKey: item.key,
								parentValue: item.label,
								label: '文件信息',
								fileType
							}
							item.children.push(obj)
							allOne.push(obj)
						}
					}
				}
			})
		} else if (item.key === 'fundManagerInfoList') {
			if (data[item.key] && Array.isArray(data[item.key]) && data[item.key].length) {
				const publicFund = ['managerName', 'idType', 'idNo', 'startDate', 'endDate', 'entryNoticeDate', 'leaveNoticeDate'] // 公募基金基金经理披露字段
				const specialFund = ['managerName', 'idType', 'idNo', 'startDate', 'endDate'] // 专户产品投资经理披露字段
				data[item.key].forEach((items, indexs) => {
					const obj = {
						parentKey: item.key,
						parentValue: item.label,
						label: fundRaiseType === '1' ? '基金经理' : '投资经理'
					}
					if (fundRaiseType === '1') {
						publicFund.forEach((property) => {
							if (property in items) {
								obj[property] = items[property]
								obj['key'] = `fundManagerInfoList${indexs + 1}`
							}
						})
					} else {
						specialFund.forEach(property => {
							if (property in items) {
								obj[property] = items[property]
							}
						})
					}
					if (obj.managerName) {
						obj.value = obj.managerName
					} else {
						obj.value = ''
					}
					item.children.push(obj)
					fundManageProperty = Object.keys(obj)
					allOne.push(obj)
				})
			}
		}
	})

	const filterData = {
		treeData,
		allOne,
		fundManageProperty
	}
	const rate = data && data.rateInfo ? data.rateInfo : {}
	if (rateListShow) {
		const rateVice = [] // 存储管理，托管，销售服务费率
		filterData.feeRateInfoList = processingRate(data, fundRaiseType)
		rate.feeRateInfoList = rate.feeRateInfoList ? rate.feeRateInfoList : []
		const manageRate = spliceIsPush(rate.feeRateInfoList.filter(item => item.feeRateType === '9'), '', '9', '', 1) // 管理费率
		const trusteeRate = spliceIsPush(rate.feeRateInfoList.filter(item => item.feeRateType === '7'), '', '7', '', 1) // 托管费率
		manageRate.forEach(items => {
			if ('feeRateAlgorithm' in rate) {
				const obj1 = {
					parentKey: 'rateInfo',
					parentValue: '费率信息',
					label: `管理费算法`,
					value: rate.feeRateAlgorithm,
					key: 'feeRateAlgorithm'
				}
				rateVice.push(obj1)
			}
			const obj2 = {
				parentKey: 'rateInfo',
				parentValue: '费率信息',
				label: `管理费率`,
				value: items.feeRate ? `${items.feeRate}${items.feeRateUnit === '2' ? '元/笔' : '%'}` : '',
				key: 'managementRate'
			}
			const obj3 = {
				parentKey: 'rateInfo',
				parentValue: '费率信息',
				label: `管理费率备注`,
				value: `${items.remark ? items.remark : ''}`,
				key: 'managementRateRemark'
			}
			rateVice.push(obj2)
			rateVice.push(obj3)
		})
		trusteeRate.forEach(items => {
			if ('custodyFeeAlgorithm' in rate) {
				const obj1 = {
					parentKey: 'rateInfo',
					parentValue: '费率信息',
					label: `托管费算法`,
					value: rate.custodyFeeAlgorithm,
					key: 'custodyFeeAlgorithm'
				}
				rateVice.push(obj1)
			}
			const obj2 = {
				parentKey: 'rateInfo',
				parentValue: '费率信息',
				label: `托管费率`,
				value: items.feeRate ? `${items.feeRate}${items.feeRateUnit === '2' ? '元/笔' : '%'}` : '',
				key: 'escrowRate'
			}
			const obj3 = {
				parentKey: 'rateInfo',
				parentValue: '费率信息',
				label: `托管费率备注`,
				value: `${items.remark ? items.remark : ''}`,
				key: 'escrowRateRemark'
			}
			rateVice.push(obj2)
			rateVice.push(obj3)
		})
		filterData.feeRateInfoList.forEach((item, index) => {
			const searchObj1 = {
				parentKey: 'rateInfo',
				parentValue: '费率信息',
				label: `${item.title}认购费率`,
				value: `${index}rengoufeilv`
			}
			const searchObj2 = {
				parentKey: 'rateInfo',
				parentValue: '费率信息',
				label: `${item.title}前端-申购费率`,
				value: `${index}qianduanshengou`
			}
			const searchObj3 = {
				parentKey: 'rateInfo',
				parentValue: '费率信息',
				label: `${item.title}后端-申购费率`,
				value: `${index}houduanshengou`
			}
			const searchObj4 = {
				parentKey: 'rateInfo',
				parentValue: '费率信息',
				label: `${item.title}赎回费率`,
				value: `${index}shuhuifeilv`
			}
			filterData.allOne.push(searchObj1)
			filterData.allOne.push(searchObj2)
			filterData.allOne.push(searchObj3)
			filterData.allOne.push(searchObj4)
			item.branchSalesSerivceRate.forEach((items) => {
				const saleObj = enumData.salesServiceFeeAlgorithm.find(val => val.typeCode === items.salesServiceFeeAlgorithm)
				const obj1 = {
					parentKey: 'rateInfo',
					parentValue: '费率信息',
					label: `${item.title}销售服务费算法`,
					value: saleObj ? saleObj.typeName : '',
					key: 'salesServiceFeeAlgorithm'
				}
				const obj2 = {
					parentKey: 'rateInfo',
					parentValue: '费率信息',
					label: `${item.title}销售服务费率`,
					value: items.feeRate ? `${items.feeRate}${items.feeRateUnit === '2' ? '元/笔' : '%'}` : '',
					key: 'salesServiceRate'
				}
				const obj3 = {
					parentKey: 'rateInfo',
					parentValue: '费率信息',
					label: `${item.title}销售服务费率备注`,
					value: `${items.remark ? items.remark : ''}`,
					key: 'salesServiceRateRemark'
				}
				rateVice.push(obj1)
				rateVice.push(obj2)
				rateVice.push(obj3)
			})
		})
		filterData.allOne.push(...rateVice)
		filterData.treeData.forEach(item => {
			if (item.key === 'rateInfo') {
				item.children = [...rateVice, ...item.children]
			}
		})
	} else {
		if ('feeRateAlgorithm' in rate) {
			const obj1 = {
				parentKey: 'rateInfo',
				parentValue: '费率信息',
				label: `管理费算法`,
				value: rate.feeRateAlgorithm,
				key: 'feeRateAlgorithm'
			}
			filterData.allOne.push(obj1)
			filterData.treeData.forEach(item => {
				if (item.key === 'rateInfo') {
					item.children.push(obj1)
				}
			})
		}
		if ('custodyFeeAlgorithm' in rate) {
			const obj1 = {
				parentKey: 'rateInfo',
				parentValue: '费率信息',
				label: `托管费算法`,
				value: rate.custodyFeeAlgorithm,
				key: 'custodyFeeAlgorithm'
			}
			filterData.allOne.push(obj1)
			filterData.treeData.forEach(item => {
				if (item.key === 'rateInfo') {
					item.children.push(obj1)
				}
			})
		}
	}
	if (fundRaiseType === '1' && branchShareList.length) {
		filterData.branchShareListProperty = branchShareListProperty
		filterData.branchShareList = branchShareList
		filterData.branchShareList.forEach((item, index) => {
			const obj1 = {
				parentKey: 'baseInfo',
				parentValue: '基础信息',
				label: `基金代码（六位）`,
				value: `${item.fundCode ? item.fundCode : ''}`,
				key: `${item.fundCode}xiashujijin${index}`
			}
			const obj2 = {
				parentKey: 'baseInfo',
				parentValue: '基础信息',
				label: `下属份额类别简称`,
				value: `${item.fundGradName ? item.fundGradName : ''}`,
				key: `jianchengxiashujijin${index}`
			}
			const obj3 = {
				parentKey: 'baseInfo',
				parentValue: '基础信息',
				label: `下属份额类别全称`,
				value: `${item.fundGradFullName ? item.fundGradFullName : ''}`,
				key: `quanchengxiashujijin${index}`
			}
			const obj4 = {
				parentKey: 'baseInfo',
				parentValue: '基础信息',
				label: `下属基金类型`,
				value: `${item.subFundTypeChine ? item.subFundTypeChine : ''}`,
				key: `leixingxiashujijin${index}`
			}
			filterData.allOne.push(obj1)
			filterData.allOne.push(obj2)
			filterData.allOne.push(obj3)
			filterData.allOne.push(obj4)
		})
	}

	if (!consignerInfo) {
		filterData.treeData = filterData.treeData.filter(item => item.key !== 'consignerInfo')
		filterData.allOne = filterData.allOne.filter(item => item.parentKey !== 'consignerInfo')
	}
	if (filterData.treeData.length) {
		filterData.firstStep = filterData.treeData[0].key
	}

	return filterData
}

// 处理费率
/*
fundRaiseType	产品类型
data	基金详细数据
*/
export function processingRate(data, fundRaiseType) {
	const rate = rateListFunc(data, fundRaiseType)
	return jsonArray(rate)
}

/*
data 基金详细数据
*/
export function rateListFunc(data, fundRaiseType) {
	if (!data.baseInfo) {
		data.baseInfo = {}
	}
	if (!data.baseInfo.branchShareList) {
		data.baseInfo.branchShareList = []
	}
	if (!data.rateInfo) {
		data.rateInfo = {}
	}
	if (!data.rateInfo.feeRateInfoList) {
		data.rateInfo.feeRateInfoList = []
	}
	const RateList = [] // 存储费率
	if (fundRaiseType === '1') { // 公募金
		if (data.baseInfo.branchShareList.length) {
			data.baseInfo.branchShareList.forEach(items => {
				if (items.subFundType === '1') { // A类下属基金
					const obj = {}
					obj.fundCode = items.fundCode // 下属基金代码
					obj.fundGradFullName = items.fundGradFullName // 下属基金全称
					obj.fundGradName = items.fundGradName // 下属基金简称
					obj.subFundType = items.subFundTypeChine // 下属基金类别中文
					obj.subFundTypeEn = items.subFundType // 下属基金类别
					// obj.title = `${obj.subFundType}-${obj.fundCode}-${obj.fundGradFullName}-` // 费率标题
					obj.title = `${obj.subFundType}-` // 费率标题

					obj.branchSalesSerivceRate = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '8' && items.subFundType === item.subFundType) // 销售服务费率,
					obj.branchSalesSerivceRate = spliceIsPush(obj.branchSalesSerivceRate, '', '8', '', 1) // 销售服务费率处理

					obj.subRateList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '1' && items.subFundType === item.subFundType) // 普通认购费率列表
					obj.subRateList = spliceIsPush(obj.subRateList, '', '1', '', 4) // 普通认购费率列表处理

					obj.subCntList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '2' && items.subFundType === item.subFundType) // 通过直销中心认购的养老金客户列表
					obj.subCntList = spliceIsPush(obj.subCntList, '', '2', '', 4) // 通过直销中心认购的养老金客户列表处理

					obj.applyRateList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '3' && items.subFundType === item.subFundType) // 前端-普通申购
					obj.applyRateList = spliceIsPush(obj.applyRateList, '', '3', '', 4) // 前端-普通申购列表处理

					obj.rearRndApplyRateList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '10' && items.subFundType === item.subFundType) // 后端-普通申购
					obj.rearRndApplyRateList = spliceIsPush(obj.rearRndApplyRateList, '', '10', '', 4) // 后端-普通申购列表处理

					obj.applyCntList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '4' && items.subFundType === item.subFundType) // 前端-通过直销中心申购的养老金客户
					obj.applyCntList = spliceIsPush(obj.applyCntList, '', '4', '', 4) // 前端-通过直销中心申购的养老金客户列表处理

					obj.rearRndApplyCntList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '11' && items.subFundType === item.subFundType) // 后端-通过直销中心申购的养老金客户
					obj.rearRndApplyCntList = spliceIsPush(obj.rearRndApplyCntList, '', '11', '', 4) // 后端-通过直销中心申购的养老金客户列表处理

					obj.ransomRateList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '5' && items.subFundType === item.subFundType) // 普通赎回
					obj.ransomRateList = spliceIsPush(obj.ransomRateList, '', '5', '', 6) // 普通赎回列表处理

					RateList.push(jsonArray(obj))
				} else {
					const obj = {}
					obj.fundCode = items.fundCode // 下属基金代码
					obj.fundGradFullName = items.fundGradFullName // 下属基金全称
					obj.fundGradName = items.fundGradName // 下属基金简称
					obj.subFundType = items.subFundTypeChine // 下属基金类别中文
					obj.subFundTypeEn = items.subFundType // 下属基金类别
					// obj.title = `${obj.subFundType}-${obj.fundCode}-${obj.fundGradFullName}-` // 费率标题
					obj.title = `${obj.subFundType}-` // 费率标题

					obj.branchSalesSerivceRate = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '8' && items.subFundType === item.subFundType) // 销售服务费率
					obj.branchSalesSerivceRate = spliceIsPush(obj.branchSalesSerivceRate, '', '8', '', 1) // 销售服务费率处理

					obj.subRateList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '1' && items.subFundType === item.subFundType) // 普通认购费率列表
					obj.subRateList = spliceIsPush(obj.subRateList, '', '1', '', 4) // 普通认购费率列表处理

					obj.applyRateList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '3' && items.subFundType === item.subFundType) // 前端-普通申购
					obj.applyRateList = spliceIsPush(obj.applyRateList, '', '3', '', 4) // 前端-普通申购列表处理

					obj.rearRndApplyRateList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '10' && items.subFundType === item.subFundType) // 后端-普通申购
					obj.rearRndApplyRateList = spliceIsPush(obj.rearRndApplyRateList, '', '10', '', 4) // 后端-普通申购列表处理

					obj.ransomRateList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '5' && items.subFundType === item.subFundType) // 普通赎回
					obj.ransomRateList = spliceIsPush(obj.ransomRateList, '', '5', '', 6) // 普通赎回列表处理

					RateList.push(jsonArray(obj))
				}
			})
		} else {
			const obj = {}
			obj.title = ''
			obj.subFundTypeEn = ''
			obj.branchSalesSerivceRate = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '8') // 销售服务费率,
			obj.branchSalesSerivceRate = spliceIsPush(obj.branchSalesSerivceRate, '', '8', '', 1) // 销售服务费率处理

			obj.subRateList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '1') // 普通认购费率列表
			obj.subRateList = spliceIsPush(obj.subRateList, '', '1', '', 4) // 普通认购费率列表处理

			obj.subCntList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '2') // 通过直销中心认购的养老金客户列表
			obj.subCntList = spliceIsPush(obj.subCntList, '', '2', '', 4) // 通过直销中心认购的养老金客户列表处理

			obj.applyRateList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '3') // 前端-普通申购
			obj.applyRateList = spliceIsPush(obj.applyRateList, '', '3', '', 4) // 前端-普通申购列表处理

			obj.rearRndApplyRateList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '10') // 后端-普通申购
			obj.rearRndApplyRateList = spliceIsPush(obj.rearRndApplyRateList, '', '10', '', 4) // 后端-普通申购列表处理

			obj.applyCntList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '4') // 前端-通过直销中心申购的养老金客户
			obj.applyCntList = spliceIsPush(obj.applyCntList, '', '4', '', 4) // 前端-通过直销中心申购的养老金客户列表处理

			obj.rearRndApplyCntList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '11') // 后端-通过直销中心申购的养老金客户
			obj.rearRndApplyCntList = spliceIsPush(obj.rearRndApplyCntList, '', '11', '', 4) // 后端-通过直销中心申购的养老金客户列表处理

			obj.ransomRateList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '5') // 普通赎回
			obj.ransomRateList = spliceIsPush(obj.ransomRateList, '', '5', '', 6) // 普通赎回列表处理

			RateList.push(jsonArray(obj))
		}
	} else if (fundRaiseType === '2') {
		const obj = {}
		obj.title = ''
		obj.subFundTypeEn = ''

		obj.branchSalesSerivceRate = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '8')
		obj.branchSalesSerivceRate = spliceIsPush(obj.branchSalesSerivceRate, '', '8', '', 1) // 销售服务费率处理

		obj.subRateList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '1')
		obj.subRateList = spliceIsPush(obj.subRateList, '', '1', '', 4) // 普通认购费率列表处理

		obj.applyRateList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '3')
		obj.applyRateList = spliceIsPush(obj.applyRateList, '', '3', '', 4) // 前端-普通申购列表处理

		obj.rearRndApplyRateList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '10')
		obj.rearRndApplyRateList = spliceIsPush(obj.rearRndApplyRateList, '', '10', '', 4) // 后端-普通申购列表处理

		obj.ransomRateList = data.rateInfo.feeRateInfoList.filter(item => item.feeRateType === '5')
		obj.ransomRateList = spliceIsPush(obj.ransomRateList, '', '5', '', 6) // 普通赎回列表处理

		RateList.push(jsonArray(obj))
	}

	return RateList
}

// 补全过短切割过长数组
// rate 要处理的数组
// subFundType 下属基金类型
// rateType 费率类型
// fundCode 基金代码
// type 数组长度类型
function spliceIsPush(rate, subFundType, rateType, fundCode, type) {
	const list = [...JSON.parse(JSON.stringify(rate))]
	let rateArray = []
	if (type === 4) { // 长度为4的类型的数组
		if (list.length > 4) {
			rateArray = JSON.parse(JSON.stringify(list.filter((item, index) => index < 4)))
		} else if (list.length < 4) {
			const addLength = list.length
			for (let i = addLength; i < 4; i++) {
				let j = 1
				j += i
				const obj = {
					feeRateType: rateType,
					feeRateId: `${j}`,
					startSection: '',
					endSection: '',
					feeRate: '',
					feeRateUnit: '1',
					subFundType: subFundType,
					fundCode: fundCode
				}
				list.push(JSON.parse(JSON.stringify(obj)))
			}
			rateArray = JSON.parse(JSON.stringify(list))
		} else if (list.length === 4) {
			rateArray = JSON.parse(JSON.stringify(list))
		}
	} else if (type === 6) { // 长度为6的类型的数组
		if (list.length > 6) {
			rateArray = JSON.parse(JSON.stringify(list.filter((item, index) => index < 6)))
		} else if (list.length < 6) {
			const addLength = list.length
			for (let i = addLength; i < 6; i++) {
				let j = 1
				j += i
				const obj = {
					feeRateType: rateType,
					feeRateId: `${j}`,
					startSection: '',
					endSection: '',
					feeRate: '',
					feeRateUnit: '1',
					subFundType: subFundType,
					fundCode: fundCode,
					belongFundRatio: '',
					belongFundRatioUnit: '1'
				}
				list.push(JSON.parse(JSON.stringify(obj)))
			}
			rateArray = JSON.parse(JSON.stringify(list))
		} else if (list.length === 6) {
			rateArray = JSON.parse(JSON.stringify(list))
		}
	} else if (type === 1) {
		if (list.length > 1) {
			rateArray = JSON.parse(JSON.stringify(list.filter((item, index) => index < 1)))
		} else if (list.length < 1) {
			const addLength = list.length
			for (let i = addLength; i < 1; i++) {
				let j = 1
				j += i
				const obj = {
					feeRateType: rateType,
					feeRateId: `${j}`,
					startSection: '',
					endSection: '',
					feeRate: '',
					feeRateUnit: '1',
					subFundType: subFundType,
					fundCode: fundCode
				}
				list.push(JSON.parse(JSON.stringify(obj)))
			}
			rateArray = JSON.parse(JSON.stringify(list))
		} else if (list.length === 1) {
			rateArray = JSON.parse(JSON.stringify(list))
		}
	}

	return JSON.parse(JSON.stringify(rateArray))
}

export const updateFileType = [
	{ title: '更新基金合同', fileRenewCode: 'upfundContract', fundRaiseType: '1' },
	{ title: '更新托管协议', fileRenewCode: 'uptrustAgreement', fundRaiseType: '1' },
	{ title: '更新招募说明书', fileRenewCode: 'upenlistExplain', fundRaiseType: '1' },
	{ title: '更新产品资料概要', fileRenewCode: 'upenlistExplainRemark', fundRaiseType: '1' },
	{ title: '更新其他文档', fileRenewCode: 'others', fundRaiseType: '1' },
	{ title: '更新季报', fileRenewCode: 'quarterly', fundRaiseType: '2' },
	{ title: '更新年报', fileRenewCode: 'annual', fundRaiseType: '2' },
	{ title: '更新重大事项临时报告', fileRenewCode: 'matters', fundRaiseType: '2' },
	{ title: '更新清算报告', fileRenewCode: 'liquidation', fundRaiseType: '2' },
	{ title: '更新合同', fileRenewCode: 'contract', fundRaiseType: '2' },
	{ title: '更新计划说明书', fileRenewCode: 'plant', fundRaiseType: '2' },
	{ title: '更新风险揭示书', fileRenewCode: 'risk', fundRaiseType: '2' },
	{ title: '更新补充协议', fileRenewCode: 'supplement', fundRaiseType: '2' },
	{ title: '更新其他文档', fileRenewCode: 'others', fundRaiseType: '2' }
]
